using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using MyApi.Entity;
using MyApi.ParamModel;

namespace MyApi.Utils
{
    // Token帮助类
    public class TokenHelper
    {
        // 生成Token
        public static string GenerateToken(TokenParameter tokenParameter, Users user)
        {
            // 声称
            var claims = new[]
            {
                new Claim(ClaimTypes.Name,user.Username),
                new Claim(ClaimTypes.Role,"admin"),
            };
            // 密钥
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenParameter.Secret));
            // 证书
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            // Json Web Token密钥
            var jwtToken = new JwtSecurityToken(tokenParameter.Issuer, null, claims, expires: DateTime.UtcNow.AddMinutes(tokenParameter.AccessExpiration), signingCredentials: credentials);
            // 密钥加密处理
            var token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
            // 返回出去
            return token;
        }
    }
}